package com.study.zzedu.fragment.home.mycourse;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.study.zzedu.R;
import com.study.zzedu.adapter.LessonAdapter;
import com.study.zzedu.base.BaseFragment;
import com.study.zzedu.entity.LessonHeaderModel;
import com.study.zzedu.entity.LessonItem;
import com.study.zzedu.ui.classchat.ClassChatActivity;
import com.study.zzedu.utils.AppConstant;
import com.study.zzedu.utils.ToastUtil;
import com.study.zzedu.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by kiros on 2020/8/25.
 */

public class HomeFragment extends BaseFragment<HomeContract.IView, HomePresenter> implements HomeContract.IView, View.OnClickListener {

    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView rc_lesson;
    private RecyclerView.LayoutManager layoutManager;
    private LessonAdapter lessonAdapter;
    private List<LessonItem> lessons = new ArrayList<>();
    int requestCount = 0;
    String lastLearnginTime = "";
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter();
    }

    @Override
    protected HomeContract.IView createView() {
        return this;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View view) {
        rc_lesson = view.findViewById(R.id.rc_lesson);
        mRefreshLayout = view.findViewById(R.id.refreshLayout);
        layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        lessonAdapter = new LessonAdapter(HomeFragment.this,getActivity(), lessons);

        rc_lesson.setLayoutManager(layoutManager);
        rc_lesson.setAdapter(lessonAdapter);
    }

    @Override
    protected void initData() {
        requestCount = 0;
        lessons.clear();
        getPresenter().getDataList(getContext());
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    protected void initListener() {
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Toast.makeText(getContext(), "正在更新进度数据", Toast.LENGTH_SHORT).show();
                getPresenter().getDataList(getContext());
                getContext().sendBroadcast(new Intent(AppConstant.ACTION_EVENT_HEAD_DATAUPDATA));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRefreshLayout.setRefreshing(false);
                    }
                },1300);
            }
        });
    }

    @Override
    public void getData(String data) {
    }

    @Override
    public void showError(String error) {
        if (null != error && !TextUtils.isEmpty(error)) {
            ToastUtil.showShortToast(error);
        }
    }

    @Override
    public void onClick(View v) {}

    @Override
    public void getHeaderInfo(String data) {
    }

    @Override
    public void getLessonList(String data) {
        try {
            lessons.clear();
            JSONObject jObject = new JSONObject(data);
            JSONArray yArray = jObject.getJSONArray("data");
            for (int y = 0; y < yArray.length(); y++) {
                String allowBeginTime = yArray.getJSONObject(y).getString("allowBeginTime");
                String allowEndTime = yArray.getJSONObject(y).getString("allowEndTime");
                JSONArray jArray = yArray.getJSONObject(y).getJSONArray("list");
                for (int i = 0; i < jArray.length(); i++) {
                    if (y == 0 && i == 0) {
                        //lastLearnginTime = jArray.getJSONObject(i).getString("lastLearnginTime");
                        lastLearnginTime = "";
                    } else {
                        lastLearnginTime = "";
                    }
                    try {
                        lessons.add(
                                new LessonItem(
                                        jArray.getJSONObject(i).getString("courseCode"),
                                        jArray.getJSONObject(i).getString("courseName"),
                                        jArray.getJSONObject(i).getString("img"),
                                        (float) jArray.getJSONObject(i).getDouble("score"),
                                        jArray.getJSONObject(i).getString("status"),
                                        jArray.getJSONObject(i).getInt("courseTotal"),
                                        jArray.getJSONObject(i).getInt("hasLearningTotal"),
                                        jArray.getJSONObject(i).getInt("testTotal"),
                                        jArray.getJSONObject(i).getInt("hasTestTotal"),

                                        jArray.getJSONObject(i).getInt("totalHour"),
                                        jArray.getJSONObject(i).getString("allowExam"),
                                        jArray.getJSONObject(i).getString("enterYear"),
                                        jArray.getJSONObject(i).getString("examType"),
                                        jArray.getJSONObject(i).getString("curTerm"),
                                        lastLearnginTime,
                                        allowBeginTime, allowEndTime, Utils.getDefaultStringValue(jArray.getJSONObject(i),"finalScore")));
                    }catch (Exception e){
                        e.toString();
                    }

                }
            }
            if (!(yArray.length() > 0)) {
                ToastUtil.showShortToast("课程列表无数据");
                return;
            }else {
                getActivity().findViewById(R.id.rl_default_home).setVisibility(View.GONE);
                if(lessons.size()>0){
                    lessonAdapter.notifyDataSetChanged();
                    getPresenter().getDataProgress(getContext());
                }
            }

        } catch (Exception e) {
            e.toString();
        }
    }

    Map<String, Object> progressMap = new HashMap<>();
    @Override
    public void getLessonProgress(String data) {
        try {
            JSONObject jObject = new JSONObject(data);
            JSONArray jArray = jObject.getJSONArray("data");

            for (int i = 0; i < jArray.length(); i++) {
                JSONObject jsonObject = jArray.getJSONObject(i);
                progressMap.clear();
                progressMap = getMapForJson(jsonObject.toString());
                //Map stringToMap =  JSONObject.parseObject(jsonObject.toString());
            }

            if (!(jArray.length() > 0)) {
                ToastUtil.showShortToast("课程进度无数据");
            }
        } catch (JSONException e) {
            e.toString();
        }
        setLessonData();
    }

    public static Map<String, Object> getMapForJson(String jsonStr){
        JSONObject jsonObject ;
        try {
            jsonObject = new JSONObject(jsonStr);

            Iterator<String> keyIter= jsonObject.keys();
            String key;
            Object value ;
            Map<String, Object> valueMap = new HashMap<String, Object>();
            while (keyIter.hasNext()) {
                key = keyIter.next();
                value = jsonObject.get(key);
                valueMap.put(key, value);
            }
            return valueMap;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    private void setLessonData() {
        for (int i = 0; i < lessons.size(); i++) {
            LessonItem li = lessons.get(i);
            if (progressMap.containsKey(li.getCourseCode())) {
                try {
                    String data = progressMap.get(li.getCourseCode()).toString();
                    JSONObject jObject = new JSONObject(data);
                        li.setTestTotal(Utils.getDefaultFloatValue(jObject,"testTotal"));
                        li.setOnlineTest(Utils.getDefaultFloatValue(jObject,"hasTestTotal"));
                        li.setCourseTotal(Utils.getDefaultFloatValue(jObject,"courseTotal"));
                        li.setProgress(Utils.getDefaultFloatValue(jObject,"hasLearningTotal"));
                } catch (Exception e) {
                    e.toString();
                }
            }
        }
        lessonAdapter.notifyDataSetChanged();
    }

}
